package com.leyou.item.web;


import com.github.pagehelper.PageInfo;
import com.leyou.common.utils.RequestHolder;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:yanjizhw@163.com
 * @date:2019-09-25 11:50
 * 描述:
 * @since:1.0.0
 */
@Controller
@RequestMapping("brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    @GetMapping("list")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> queryBrand(@RequestParam(value = "key", required = false) String key,
                                                     @RequestParam(value="page", defaultValue = "1") Integer page){

        Map<String, Object> map = new HashMap<>();

        int pageSize = 12; //每页显示条数

        PageInfo<Brand> info = brandService.queryBrand(key, page, pageSize);


        long totalPage = info.getTotal() / pageSize;

        if (info.getTotal() % pageSize != 0){
            totalPage ++;
        }

        // 封装数据，并返回
        map.put("page", page);
        map.put("pageSize", pageSize);
        map.put("totalPage", totalPage);
        map.put("list", info.getList());

        return ResponseEntity.ok(map);

    }

    @PostMapping("addBrand")
    public String addBrand(Brand brand, @RequestParam(value = "categoryId") Integer categoryId,
                           @RequestParam(value = "logo", required = false) MultipartFile image){

        brandService.addBrand(brand, categoryId, image);

        return "brand";
    }

    @ResponseBody
    @GetMapping("queryCategoryIdByBrandId")
    public ResponseEntity<Integer> queryCategoryIdByBrandId(Brand brand){

        Integer cid = brandService.queryCategoryIdByBrandId(brand);

        return ResponseEntity.ok(cid);
    }

    @PostMapping("modifyBrand")
    public String modifyBrand(Brand brand, @RequestParam(value = "categoryId") Integer categoryId,
                              @RequestParam(value = "logo", required = false) MultipartFile image){

        brandService.modifyBrand(brand, categoryId, image);

        return "brand";
    }

    @PostMapping("moveBrand")
    public String moveBrand(Brand brand){

        brandService.moveBrand(brand);

        return "brand";
    }
}
